package com.mti.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mti.dao.kmmodel.GisModel;
import com.mti.dao.model.KmAlarmAreaEntity;
import com.mti.dao.qo.KmAlarmAreaQO;
import com.mti.mapper.KmAlarmAreaMapper;
import com.mti.service.KmAlarmAreaService;
import io.jsonwebtoken.lang.Collections;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 手机预警和人脸识别预警设置过滤 服务实现类
 * </p>
 *
 * @author hf
 * @since 2020-11-18
 */
@Slf4j
@Service
public class KmAlarmAreaServiceImpl extends ServiceImpl<KmAlarmAreaMapper, KmAlarmAreaEntity> implements KmAlarmAreaService {

    @Override
    public boolean authIsInArea(KmAlarmAreaQO qo) {
        List<String> list = this.list().stream().map(KmAlarmAreaEntity::getAlarmRange).collect(Collectors.toList());
        qo.setGisModels(getGisModels(list));
        return this.getBaseMapper().authIsInArea(qo);
    }

    @Override
    public List<GisModel> getAreaList() {
        List<String> list = this.list().stream().map(KmAlarmAreaEntity::getAlarmRange).collect(Collectors.toList());
        return getGisModels(list);
    }

    /**
     * 解析坐标数据
     *
     * @param list
     * @return
     */
    private List<GisModel> getGisModels(List<String> list) {
        List<GisModel> gisModels = new ArrayList<>();
        try {
            if (Collections.isEmpty(list)) {
                return null;
            }
            for (int i = 0; i < list.size(); i++) {
                GisModel gisModel = new GisModel();
                JSONObject jsonObject = JSONObject.parseObject(list.get(i));
                JSONObject jobj = JSONObject.parseObject(jsonObject.getString("GEOM"));
                JSONArray coordinates = jobj.getJSONArray("coordinates").getJSONArray(0);
                StringBuilder temp = new StringBuilder("POLYGON");
                temp.append("((");
                for (int z = 0; z < coordinates.size(); z++) {
                    JSONArray ja = coordinates.getJSONArray(z);
                    String locateInfoStr = ja.get(0) + " " + ja.get(1);
                    temp.append(locateInfoStr).append(",");
                }
                temp.deleteCharAt(temp.length() - 1);
                temp.append("))");
                String geomText = temp.toString();
                gisModel.setGeom(geomText);
                gisModels.add(gisModel);
            }
        } catch (Exception e) {
            log.error("KmAlarmAreaServiceImpl-解析坐标数据失败", e);
        }
        return gisModels;
    }
}


